/*
	Copyright (C) 2009 jungil Han <jungil.Han@gmail.com>

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <QtGui/QApplication>
#include <qt_windows.h>

#include "Dialog/mkMainDialog.h"

bool IsDuplicatedExecution();

int main(int argc, char *argv[])
{	
	if ( IsDuplicatedExecution() ) {
		wchar_t szAppName[64] = {0, };
		QString strAppName = QString( "Monkey Hotkey " ) + QString( MONKEY_VERSION );
		strAppName.toWCharArray( szAppName );
		
		HWND hWnd = FindWindowW( NULL,  szAppName );
		if ( hWnd ) { 
			SendMessage( hWnd, WM_APP + 1, 0, 0 );
		}

		return -1;
	}
	
	QApplication app(argc, argv);
	QApplication::setQuitOnLastWindowClosed(false);
	
	mkMainDialog mainDialog( NULL, Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint );

	QObject::connect( &app, SIGNAL( aboutToQuit() ), &mainDialog, SLOT( SlotQuit() ));

	mainDialog.InitDialog();
	
	QString strArgument = argv[1];
	if ( strArgument == "/autorun" ) {
		mainDialog.close();
	} else {
		mainDialog.show();
	}

	return app.exec();
}

bool IsDuplicatedExecution()
{
	wchar_t szMutexName[64] = {0, };
	QString strMutexName = "MonkeyHotkey";
	strMutexName.toWCharArray( szMutexName );

        HANDLE hMutex = CreateMutex ( NULL, TRUE, szMutexName );

        bool nIsFound = false;
			
        if ( GetLastError() == ERROR_ALREADY_EXISTS )
                nIsFound = true;

        if ( hMutex )
                ReleaseMutex( hMutex );

	return nIsFound;
}
